package com.zhilehuo.pretask.ui.library

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhilehuo.pretask.R
import com.zhilehuo.pretask.adapter.ArticleAdapter
import com.zhilehuo.pretask.adapter.Category
import com.zhilehuo.pretask.adapter.CategoryAdapter
import com.zhilehuo.pretask.adapter.DifficultyAdapter
import com.zhilehuo.pretask.databinding.FragmentLibraryBinding
import timber.log.Timber

/**
 * @Description: 文库页
 * @Author: Realnt
 * @Date:
 */
class LibraryFragment : Fragment() {
    private lateinit var binding: FragmentLibraryBinding
    private val viewModel: LibraryViewModel by viewModels()

    /* 适配器 */
    private lateinit var categoryAdapter: CategoryAdapter
    private lateinit var difficultyAdapter: DifficultyAdapter
    private lateinit var articleAdapter: ArticleAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val window = requireActivity().window
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.isAppearanceLightStatusBars = true
        windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        requireActivity().window.statusBarColor = Color.parseColor("#FAFFF2")
        binding = FragmentLibraryBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupAdapters() // 初始化适配器
        setupObservers() // 初始化数据观察
        setupListeners() // 初始化监听器
    }


    private fun setupAdapters() {
        /* 分类适配器 */
        categoryAdapter = CategoryAdapter { category ->
            viewModel.selectedTypeId.value = category.id
            viewModel.refreshArticles()
            handleCategoryClick(category)
        }
        binding.categoryList.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = categoryAdapter
        }

        /* 难度适配器 */
        difficultyAdapter = DifficultyAdapter { difficulty ->
            viewModel.selectedDifficulty.value = difficulty
            viewModel.refreshArticles()

        }
        binding.difficultyRecycler.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
            adapter = difficultyAdapter
        }

        /* 文章适配器 */
        articleAdapter = ArticleAdapter()
        binding.articleRecycler.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = articleAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (!recyclerView.canScrollVertically(1)) {
                        viewModel.loadArticles()
                    }
                }
            })
        }
    }

    /**
     * @Description: 初始化数据观察
     * @Param  :
     * @Return  :
     */
    private fun setupObservers() {
        viewModel.categories.observe(viewLifecycleOwner) { categories ->
            categoryAdapter.submitList(categories)
        }

        viewModel.difficulties.observe(viewLifecycleOwner) { difficulties ->
            difficultyAdapter.submitList(difficulties)
            difficultyAdapter.setCurrentDifficulty(viewModel.selectedDifficulty.value?: 650)
            scrollToSelectedDifficulty()
        }

        viewModel.selectedDifficulty.observe(viewLifecycleOwner) { difficulty ->
            binding.difficultyRecycler.post {
                binding.difficultyRecycler.smoothScrollToPosition(difficulty / 5)
                difficultyAdapter.setCurrentDifficulty(difficulty)
            }
        }

        viewModel.articles.observe(viewLifecycleOwner) { articles ->
            articleAdapter.submitList(articles)
            binding.rlArticle.isRefreshing = false
        }

        viewModel.errorMessage.observe(viewLifecycleOwner) { message ->
            Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
            binding.rlArticle.isRefreshing = false
        }

        viewModel.successMessage.observe(viewLifecycleOwner) { message ->
            //Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * @Description: 初始化监听器
     * @Param  :
     * @Return  :
     */
    private fun setupListeners() {
        binding.rlArticle.setOnRefreshListener {
            viewModel.refreshArticles()
        }
    }

    /**
     * @Description: 点击分类触发
     * @Param category : 点击的分类
     * @Return  :
     */
    private fun handleCategoryClick(category: Category) {
        // 遍历列表并执行操作
        val currentList = viewModel.categories.value ?: emptyList() // 获取当前列表，如果为空则初始化为空列表
        val updatedList = currentList.toMutableList() // 将不可变列表转换为可变列表
        updatedList.forEach { item ->
            if (item.id == category.id) {
                // 对当前点击的项执行操作
                println("Clicked category: ${item.type}")
            } else {
                // 对其他项执行操作
                println("Other category: ${item.type}")
            }
        }
    }

    /**
     * @Description: 滚动到选择的难度
     * @Param  :
     * @Return  :
     */
    private fun scrollToSelectedDifficulty() {
        val selectedValue = viewModel.selectedDifficulty.value ?: return
        val difficulties = viewModel.difficulties.value ?: return
        // 找到选中值在列表中的位置
        val position = difficulties.indexOf(selectedValue) + 5
        if (position != -1) {
            binding.difficultyRecycler.post {
                // 确保平滑滚动到正确位置
                binding.difficultyRecycler.smoothScrollToPosition(position)
            }
        }
    }
}